import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

# 读取数据集
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)

# 打印数据集的前5行
print(df.head())

# 使用matplotlib绘制企鹅种类的分布条形图
plt.figure(figsize=(10, 6))
sns.countplot(x='Species', data=df)
plt.xlabel('Species')
plt.ylabel('Count')
plt.title('Distribution of Penguin Species')
plt.show()

# 使用seaborn绘制箱型图，展示不同种类企鹅的FlipperLength、CulmenLength和CulmenDepth分布
plt.figure(figsize=(12, 6))
sns.boxplot(data=df, x='Species', y='FlipperLength')
plt.title('Flipper Length Distribution by Species')
plt.show()

plt.figure(figsize=(12, 6))
sns.boxplot(data=df, x='Species', y='CulmenLength')
plt.title('Culmen Length Distribution by Species')
plt.show()

plt.figure(figsize=(12, 6))
sns.boxplot(data=df, x='Species', y='CulmenDepth')
plt.title('Culmen Depth Distribution by Species')
plt.show()

# 显示缺失值的行
print(df.isnull().sum())

# 删除缺失值的行
df_clean = df.dropna()

# 准备训练数据
# 分离特征和标签
X = df_clean[['CulmenLength', 'CulmenDepth', 'FlipperLength']]
y = df_clean['Species']

# 分割数据为训练集和测试集，测试集占30%
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 训练逻辑回归模型
# 创建一个多类别逻辑回归模型
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=1000)

# 训练模型
model.fit(X_train, y_train)

# 评估模型
# 预测测试集的标签
y_pred = model.predict(X_test)

# 计算模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Model Accuracy: {accuracy:.2f}')